package com.neusoft.controller;

import com.alibaba.fastjson.JSON;
import com.neusoft.dto.UserDto;
import com.neusoft.entity.UsersEntity;
import com.neusoft.mapper.UsersMapper;
import com.neusoft.utils.JwtService;
import com.neusoft.utils.MyJWT;
import com.neusoft.utils.SqlSessionFactoryUtils;
import com.neusoft.vo.UserVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/users")
public class UserController {
    @Resource
    JwtService jwtService;
    @Resource
    UsersMapper usersMapper;
    @PostMapping("/")
    public Integer regUser(@RequestBody UserDto userDto){
        userDto.getUser().setBio("");
        userDto.getUser().setImage("");
        Integer effected_rows = usersMapper.insert(userDto.getUser());
        return effected_rows;
    }
    @PostMapping("/login")
    public UserVo loginUser(@RequestBody UserDto userDto){

        UsersEntity usersEntity = usersMapper.loginUser(userDto.getUser());
        if(usersEntity != null){
            UserVo userVo = new UserVo();
            try {
                BeanUtils.copyProperties(userVo, usersEntity);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
            System.out.println(usersEntity.getId().toString());

//            Map<String,String> map = new HashMap<String, String>();
//            map.put("userid", usersEntity.getId().toString());
//            String jsonMap = JSON.toJSONString(map);
//            String token = MyJWT.makeSecret(jsonMap);

            String token = jwtService.toToken(usersEntity);

            userVo.setToken(token);
            return userVo;
        }
        else{
            return null;
        }

    }
}
